<template>
  <!--角色编辑-->
  <div class="role-edit">
    <el-form
      ref="ruleFormRef"
      style="max-width: 99%"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <div class="role-edit-header">
        <el-form-item>
          <el-col :span="11">
            <el-form-item label="角色名称:" prop="roleName">
              <el-input v-model="ruleForm.roleName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="角色状态:" prop="state">
              <el-select v-model="ruleForm.state">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="ruleForm.description" />
        </el-form-item>
      </div>
      <div class="role-edit-middle">
        <el-form-item label="选择权限" prop="functionIds" label-position="top">
          <div style="height: 380px; width: 100%">
            <el-splitter>
              <el-splitter-panel size="20%">
                <div class="panel-left">
                  <div
                    class="panel-left-item"
                    v-for="(item1, index1) in PermissionDataList"
                    :key="index1"
                    @click="permissionTab(item1)"
                  >
                    {{ item1.name }}
                  </div>
                </div>
              </el-splitter-panel>
              <el-splitter-panel :min="200">
                <div
                  class="panel-right"
                  v-for="(item2, index2) in selecctPermData.children"
                  :key="index2 + ''"
                >
                  <div class="pannel-right-tilte">
                    {{ item2.name }}
                  </div>
                  <div class="check-box">
                    <el-checkbox-group v-model="ruleForm.routeIds">
                      <el-checkbox
                        v-for="(item3, index3) in item2.children"
                        :key="index3 + ''"
                        :value="item3.id"
                      >
                        {{ item3.name }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-splitter-panel>
            </el-splitter>
          </div>
        </el-form-item>
      </div>

      <div class="role-edit-footer">
        <el-form-item>
          <div class="role-edit-button">
            <el-button
              @click="resetForm(ruleFormRef)"
              class="button-canncl button"
              >取消</el-button
            >
            <el-button
              color="rgb(222, 41, 16)"
              type="primary"
              @click="submitForm(ruleFormRef)"
              class="button-confirm button"
            >
              确定
            </el-button>
          </div>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";

import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router"; // 引入useRouter函数
import http from "@/request/request";
// import { Data } from "@/request/pageData";

const router = useRouter(); // 获取路由实例
const route = useRoute();

interface PermissionData {
  id: number;
  name: string;
  children: PermissionData[];
}

interface RuleForm {
  roleName: string;
  state: number;
  description: string;
  routeIds: number[];
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<RuleForm>({
  roleName: "",
  state: 1,
  description: "",
  routeIds: [],
});
const PermissionDataList = ref<PermissionData[]>();
const selecctPermData = ref<PermissionData>({
  id: 1,
  name: "",
  children: [],
});
const isCreate = ref(true);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const roleId = ref<any>(0);
// 校验器
const rules = reactive<FormRules<RuleForm>>({
  roleName: [
    { required: true, message: "请填写角色名称", trigger: "blur" },
    { min: 3, max: 20, message: "角色名称在3-20个字符", trigger: "blur" },
  ],
  routeIds: [{ required: true, message: "请选择权限" }],
});
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isCreate.value) {
        createRole();
      } else {
        updateRole();
      }

      router.push("/role");
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/role");
};
// 获取所有权限列表
const getAllPermission = async () => {
  try {
    const { data } = await http.get<PermissionData[]>(
      "/api/system/getAllRouteList"
    );
    PermissionDataList.value = data;
    selecctPermData.value = data[0];
  } catch (err) {
    console.log(err);
  }
};
const permissionTab = (p: PermissionData) => {
  selecctPermData.value = p;
};
// 创建角色
const createRole = () => {
  try {
    http.post("/api/system/createRole", ruleForm.value);
  } catch (err) {
    console.log(err);
  }
};
// 更新角色
const updateRole = () => {
  try {
    http.post("/api/system/updateRole", {
      ...ruleForm.value,
      id: roleId.value,
    });
  } catch (err) {
    console.log(err);
  }
};
// 查询角色信息
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getRolePermission = async (id: any) => {
  try {
    const { data } = await http.get<RuleForm>("/api/system/getRoleDetail", {
      roleId: id,
    });
    ruleForm.value = data;
  } catch (err) {
    console.log(err);
  }
};
//-----------------------------生命周期-------------------------------//
onMounted(() => {
  // 查询权限列表
  getAllPermission();
  roleId.value = route.query.id;
  // 判断是否有参数传递，如果有参数传递，则进行请求接口，视为修改，否则视为添加
  if (roleId.value && roleId.value != 0) {
    isCreate.value = false;
    getRolePermission(roleId.value);
  }
});
</script>

<style lang="less" scoped>
.role-edit-header {
  background-color: rgb(255, 255, 255);
  //   padding: 20px;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 10px;
}
.role-edit-middle {
  background-color: rgb(255, 255, 255);
  padding: 20px;
  margin-top: 10px;
  .panel-left {
    display: flex;
    align-items: start;
    flex-direction: column;
    height: 100%;
    .panel-left-item {
      margin-left: 20px;
      cursor: pointer;
    }
  }
  .panel-right {
    text-align: start;
    margin-left: 20px;
    .pannel-right-tilte {
      font-weight: 600;
    }
    .check-box {
      margin-left: 20px;
      margin-bottom: 20px;
    }
  }
}
.role-edit-footer {
  margin-top: 10px;
  padding-top: 20px;
  height: 60px;
  background-color: rgb(255, 255, 255);
}
.role-edit-button {
  margin-left: 72%;
  .el-button {
    width: 150px;
  }
}
</style>